package com.youkeyi.ddy.cloud.application.business.hr.job;

import com.youkeyi.ddy.cloud.common.api.basic.hr.employee.employee.HrEmployeeCloudService;
import com.youkeyi.ddy.cloud.common.api.basic.hr.employee.employee.dto.HrEmployeeListCloudDto;
import com.youkeyi.ddy.cloud.common.api.basic.hr.employee.employee.dto.HrEmployeeListItemCloudDto;
import com.youkeyi.ddy.cloud.common.api.basic.hr.employee.employee.param.HrEmployeeQueryCloudParam;
import com.youkeyi.ddy.cloud.common.utils.SystemDateUtils;
import com.youkeyi.ddy.cloud.common.wx.applet.message.service.WxMessageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * EmployeeBirthdayRemindJob
 *
 * @Author liuxiawang
 * @Date 2024/6/29 2:16 PM
 * @Location shenzhen.china
 */
@Slf4j
@Component
public class EmployeeBirthdayRemindJob {

    @Autowired
    private HrEmployeeCloudService hrEmployeeCloudService;
    @Autowired
    private WxMessageService wxMessageService;

    /**
     * 规定定时任务执行频率： 每天的09:01:00执行
     *
     * 生日快到的第30、15、7、当天，四次提醒，发微信订阅消息
     */
    // @Scheduled(cron = "0 1 9 * * ?")
    private void employeeBirthdayRemind() {
        log.info("员工生日提醒");

        // 查询30天内生日的员工
        HrEmployeeQueryCloudParam employeeQueryCloudParam = new HrEmployeeQueryCloudParam();
        employeeQueryCloudParam.setBirthdayBegin(SystemDateUtils.localDateTime2Long(LocalDateTime.of(LocalDate.now(), LocalTime.MIN)));
        employeeQueryCloudParam.setBirthdayEnd(SystemDateUtils.localDateTime2Long(LocalDateTime.of(LocalDate.now().plusDays(30), LocalTime.MAX)));
        HrEmployeeListCloudDto employeeDtos = hrEmployeeCloudService.queryForBirthday(employeeQueryCloudParam);
        if (null != employeeDtos && CollectionUtils.isNotEmpty(employeeDtos.getRows())) {
            // 查询部门下的员工数据
            List<String> departmentKeys = employeeDtos.getRows().stream().map(HrEmployeeListItemCloudDto::getDepartmentKey).collect(Collectors.toList());
            HrEmployeeQueryCloudParam departmentEmployeeQueryCloudParam = new HrEmployeeQueryCloudParam();
            departmentEmployeeQueryCloudParam.setDepartmentKeys(departmentKeys);
            HrEmployeeListCloudDto departmentEmployeeDtos = hrEmployeeCloudService.query(departmentEmployeeQueryCloudParam);
            Map<String, List<String>> departmentEmployeeKeys = new HashMap<>();
            if (null != departmentEmployeeDtos && CollectionUtils.isNotEmpty(departmentEmployeeDtos.getRows())) {
                // 通过部门分组员工
                departmentEmployeeKeys.putAll(departmentEmployeeDtos.getRows().stream().collect(Collectors.groupingBy(HrEmployeeListItemCloudDto::getDepartmentKey, Collectors.mapping(HrEmployeeListItemCloudDto::getEmployeePrimaryKey, Collectors.toList()))));
            }

            employeeDtos.getRows().forEach(employeeDto -> {
                // 判断当前员工的生日是不是距离现在30、15、7、当天的
                Long epochDay = SystemDateUtils.getEpochDays(employeeDto.getBirthday(), System.currentTimeMillis());
                if (30 == epochDay || 15 == epochDay || 7 == epochDay || 0 == epochDay) {
                    if (departmentEmployeeKeys.containsKey(employeeDto.getDepartmentKey())) {
                        List<String> keys = departmentEmployeeKeys.get(employeeDto.getDepartmentKey());
                        keys.remove(employeeDto.getEmployeePrimaryKey());
                        if (CollectionUtils.isNotEmpty(keys)) {
                            wxMessageService.subscribeSendForBirthday(
                                    keys,
                                    0 != epochDay ? String.format("%d天后就生日了，记得送上祝福哟", epochDay) : "今天就是他（她）生日了，记得送上祝福哟",
                                    employeeDto.getName(),
                                    employeeDto.getBirthday()
                            );
                        }
                    }
                }
            });
        }
    }
}
